import re
from django_redis import get_redis_connection
from rest_framework import serializers
from users.models import User


class AuthSerializer(serializers.ModelSerializer):
    sms_code = serializers.CharField(label="短信验证码", write_only=True)
    token = serializers.CharField(label="token", read_only=True)

    class Meta:
        model = User
        fields = ("id", "username", "mobile", "sms_code", "avatar", "password", "token")
        extra_kwargs = {
            "password": {
                "write_only": True,
                "required": True
            }
        }

    def validate_mobile(self, value):
        if not re.match(r'^1[345789]\d{9}$', value):
            raise serializers.ValidationError('手机号格式不正确')
        return value

    def validate(self, attrs):
        redis_conn = get_redis_connection('verify_code')
        mobile = attrs.get("mobile")
        sms = attrs.get('sms_code')
        sms_server = redis_conn.get("sms_%s" % mobile)
        if sms_server is None:
            raise serializers.ValidationError("验证码过期")
        if sms != sms_server.decode():
            raise serializers.ValidationError("验证码错误")
        return attrs

    def create(self, validated_data):
        del validated_data['sms_code']
        user = super().create(validated_data)
        user.set_password(validated_data["password"])
        user.save()
        from rest_framework_jwt.settings import api_settings
        # 组织payload数据的方法
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # 生成jwt token数据的方法
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        # 组织payload数据
        payload = jwt_payload_handler(user)
        # 生成jwt token
        token = jwt_encode_handler(payload)
        user.token = token
        return user


# class LoginUserSerializer(serializers.ModelSerializer):
#     token = serializers.CharField(read_only=True)
#     # username = serializers.CharField()
#     class Meta:
#         model = User
#         fields = ("id", "username", "mobile", "avatar", "password", "token")
#         extra_kwargs = {
#             "password": {
#                 "write_only": True,
#                 "required": True
#             },
#             "mobile": {
#                 "read_only": True,
#                 "required": False
#             },
#             "avatar": {
#                 "read_only": True,
#             },
#
#         }
#
#     def validate(self, attrs):
#         username = attrs.get('username')
#         password = attrs.get('password')
#         try:
#             user = User.objects.get(username=username)
#         except User.DoesNotExist:
#             raise serializers.ValidationError('用户名或者密码错误')
#
#         else:
#             if not user.check_password(password):
#                 raise serializers.ValidationError('用户名或者密码错误')
#
#         attrs['user'] = user
#
#         return attrs
#
#     def create(self, validated_data):
#         user = validated_data.get('user')
#
#         from rest_framework_jwt.settings import api_settings
#         # 组织payload数据的方法
#         jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
#         # 生成jwt token数据的方法
#         jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
#         # 组织payload数据
#         payload = jwt_payload_handler(user)
#         # 生成jwt token
#         token = jwt_encode_handler(payload)
#         user.token = token
#         return user